// Package middleware 网络请求模块
package middleware

import (
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
)

type HttpMiddleWare struct {
	TimeOut int
	Header  map[string]string
}

// New 构造默认值
func (middleware *HttpMiddleWare) New() *HttpMiddleWare {
	if middleware.TimeOut == 0 {
		middleware.TimeOut = 30 //超时时间，秒
	}
	if len(middleware.Header) == 0 {
		middleware.Header = map[string]string{ //设置请求头
			"Content-Type": "application/x-www-form-urlencoded",
		}
	}
	return middleware
}

// Vget get请求
func (middleware *HttpMiddleWare) Vget(urls string) (string, map[string][]string) {
	client := &http.Client{
		Timeout: time.Second * time.Duration(middleware.TimeOut),
	}
	reqest, err := http.NewRequest("GET", urls, nil)
	if err != nil {
		return "", nil
	}
	for key, one := range middleware.Header {
		reqest.Header.Add(key, one)
	}
	response, err := client.Do(reqest)
	if err != nil {
		return "", nil
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return "", nil
	}
	head := response.Header

	return string(body), head
}

// Vpost post请求
func (middleware *HttpMiddleWare) Vpost(urls string, postdata map[string]interface{}) (string, map[string][]string) {
	client := &http.Client{
		Timeout: time.Second * time.Duration(middleware.TimeOut),
	}
	data := url.Values{}
	contentType := ""
	for name, value := range postdata {
		data.Set(name, ToString(value))

	}
	for key, one := range middleware.Header {
		if strings.ToLower(key) == "content-type" {
			contentType = strings.ToLower(ToString(one))
		}
	}
	reader := strings.NewReader(data.Encode())
	if contentType == "application/json" {
		jsonStr := MapToJson(postdata)
		reader = strings.NewReader(jsonStr)
	}
	reqest, err := http.NewRequest("POST", urls, reader)
	if err != nil {
		return "", nil
	}
	if contentType == "" {
		reqest.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	}
	for key, one := range middleware.Header {
		reqest.Header.Add(key, one)
	}
	response, err := client.Do(reqest)
	if err != nil {
		return "", nil
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return "", nil
	}
	head := response.Header
	return string(body), head
}
